﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Collections;

namespace YJY_DMZS.SupplyChain
{
    public partial class FrmInStock : XtraForm
    {
        public FrmInStock()
        {
            InitializeComponent();
            InitGrid();
        }

        /// <summary>
        /// 初始网格显示
        /// </summary>
        private void InitGrid()
        {
            grvBody.IndicatorWidth = grvBody.IndicatorWidth == -1 ? 40 : grvBody.IndicatorWidth;
            grvBody.OptionsView.ShowIndicator = true;

            CommonControl.DxGridHelper.InitGridStyle(grvBody);
        }

        /// <summary>
        /// 单据ID,非零为修改单据
        /// </summary>
        /// <param name="ID"></param>
        public FrmInStock(long ID)
            : this()
        {
            this.ID = ID;
        }
        public long ID;
        DMZS.Model.DlyndxOrder.OrderType OrderType;
        private int DepartmentID;
        private string DepartmentCode;
        private string DepartmentName;
        private int SupplierID;
        private string SupplierCode;
        private string SupplierName;
        private int OrderTypeID;

        private DataTable Barcodes;


        private void FrmInStock_Load(object sender, EventArgs e)
        {
            this.OrderType = DMZS.Model.DlyndxOrder.OrderType.RKD;
            var bllVchtype = new DMZS.BLL.Vchtype();
            OrderTypeID = bllVchtype.GetOrderTypeID(OrderType);
            if (OrderTypeID == 0)
            {
                XtraMessageBox.Show("获取单据类型失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                this.Close();
                return;
            }

            if (ID <= 0)
            {
                NewRecord();
            }
            else
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            var bll = new DMZS.BLL.InStock();
            var row = bll.GetHead(ID);

            if (row != null)
            {
                DepartmentID = Convert.ToInt32(row["DepartmentID"]);
                DepartmentCode = row["DepartmentCode"].ToString();
                DepartmentName = row["DepartmentName"].ToString();
                SupplierID = row["SupplierID"] == DBNull.Value ? 0 : Convert.ToInt32(row["SupplierID"]);
                SupplierCode = row["SupplierCode"].ToString();
                SupplierName = row["SupplierName"].ToString();

                txtCode.Text = row["Number"].ToString();
                txtOperator.Text = row["InputNo"].ToString();
                bteDepartment.Text = DepartmentName;
                bteSupplier.Text = SupplierName;
                txtCreator.Text = row["etypeid"].ToString();
                txtChecker.Text = row["checke"].ToString();
                txtCreateTime.Text = string.Format("{0:yyyy-MM-dd hh:mm:ss}", row["Date"]);
                txtCheckTime.Text = row["checkeDate"] == DBNull.Value ? "" : string.Format("{0:yyyy-MM-dd hh:mm:ss}", row["checkeDate"]);

                chkIsScan.CheckedChanged -= new EventHandler(chkIsScan_CheckedChanged);
                chkIsScan.Checked = Convert.ToBoolean(row["isScan"]);
                chkIsScan.CheckedChanged += new EventHandler(chkIsScan_CheckedChanged);

                RefreshEnabled(Convert.ToInt32(row["draft"]));
                RefreshGrid(chkIsScan.Checked);

                var dt = bll.GetBody(ID);
                if (dt != null)
                {
                    grdBody.DataSource = dt;
                }
                else
                {
                    pnlTools.Enabled = false;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                    XtraMessageBox.Show("加载表体失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
                var dtBarcode = bll.GetBarcode(ID, OrderType);
                if (dtBarcode != null)
                {
                    Barcodes = dtBarcode;
                }
                else
                {
                    pnlTools.Enabled = false;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                    XtraMessageBox.Show("加载关联条码信息失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
            }
            else
            {
                pnlTools.Enabled = false;
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                XtraMessageBox.Show("加载表头失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }

        private void NewRecord()
        {
            if (!LoadNewCode())
            {
                return;
            }
            InitNew();

            bteDepartment.Focus();
        }

        private void cbbOrderType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!LoadNewCode())
            {
                return;
            }
            InitNew();

            bteDepartment.Focus();
        }

        private void InitNew()
        {
            ID = 0;
            DepartmentID = 0;
            DepartmentCode = string.Empty;
            DepartmentName = string.Empty;
            SupplierID = 0;
            SupplierCode = string.Empty;
            SupplierName = string.Empty;

            txtOperator.Text = string.Empty;
            bteDepartment.Text = string.Empty;
            bteSupplier.Text = string.Empty;
            txtChecker.Text = string.Empty;
            mmoRemark.Text = string.Empty;
            txtCreateTime.Text = string.Empty;
            txtCheckTime.Text = string.Empty;

            //chkIsScan.Checked = false;

            RefreshEnabled(-1);
            RefreshGrid(chkIsScan.Checked);

            var bll = new DMZS.BLL.InStock();
            var dt = bll.GetBody(-1);
            if (dt != null)
            {
                grdBody.DataSource = dt;
            }
            else
            {
                pnlTools.Enabled = false;
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                XtraMessageBox.Show("初始表体失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            var dtBarcode = bll.GetBarcode(-1, OrderType);
            if (dtBarcode != null)
            {
                Barcodes = dtBarcode;
            }
            else
            {
                pnlTools.Enabled = false;
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                XtraMessageBox.Show("初始关联条码信息失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }

        private void RefreshEnabled(int status)
        {
            switch (status)
            {
                case 0:
                    btnSave.Enabled = true;
                    btnDelete.Enabled = true;
                    btnCheck.Enabled = true;
                    btnUnCheck.Enabled = false;
                    btnClose.Enabled = false;
                    btnScan.Enabled = true;

                    chkIsScan.Properties.ReadOnly = true;

                    txtOperator.Properties.ReadOnly = false;
                    bteDepartment.Properties.ReadOnly = false;
                    bteDepartment.Properties.Buttons[0].Enabled = true;
                    bteSupplier.Properties.ReadOnly = false;
                    bteSupplier.Properties.Buttons[0].Enabled = true;
                    mmoRemark.Properties.ReadOnly = false;
                    txtCreator.Properties.ReadOnly = true;
                    txtChecker.Properties.ReadOnly = false;

                    grvBody.OptionsBehavior.Editable = true;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

                    grvBody.DoubleClick += new EventHandler(grvBody_DoubleClick);

                    lblStatus.Text = "待审";
                    break;
                case 1:
                    btnSave.Enabled = false;
                    ;
                    btnDelete.Enabled = false;
                    btnCheck.Enabled = false;
                    btnUnCheck.Enabled = true;
                    btnClose.Enabled = true;
                    btnScan.Enabled = false;

                    chkIsScan.Properties.ReadOnly = true;

                    txtOperator.Properties.ReadOnly = true;
                    bteDepartment.Properties.ReadOnly = true;
                    bteDepartment.Properties.Buttons[0].Enabled = false;
                    bteSupplier.Properties.ReadOnly = true;
                    bteSupplier.Properties.Buttons[0].Enabled = false;
                    mmoRemark.Properties.ReadOnly = true;
                    txtCreator.Properties.ReadOnly = true;
                    txtChecker.Properties.ReadOnly = true;

                    grvBody.OptionsBehavior.Editable = false;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;

                    lblStatus.Text = "已审";
                    break;
                case 2:
                    btnSave.Enabled = false;
                    btnDelete.Enabled = false;
                    btnCheck.Enabled = false;
                    btnUnCheck.Enabled = false;
                    btnClose.Enabled = false;
                    btnScan.Enabled = false;

                    chkIsScan.Properties.ReadOnly = true;

                    txtOperator.Properties.ReadOnly = true;
                    bteDepartment.Properties.ReadOnly = true;
                    bteDepartment.Properties.Buttons[0].Enabled = false;
                    bteSupplier.Properties.ReadOnly = true;
                    bteSupplier.Properties.Buttons[0].Enabled = false;
                    mmoRemark.Properties.ReadOnly = true;
                    txtCreator.Properties.ReadOnly = true;
                    txtChecker.Properties.ReadOnly = true;

                    grvBody.OptionsBehavior.Editable = false;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;

                    lblStatus.Text = "已关闭";
                    break;
                default:
                    btnSave.Enabled = true;
                    btnDelete.Enabled = false;
                    btnCheck.Enabled = false;
                    btnUnCheck.Enabled = false;
                    btnClose.Enabled = false;
                    btnScan.Enabled = true;

                    chkIsScan.Properties.ReadOnly = false;

                    txtOperator.Properties.ReadOnly = false;
                    bteDepartment.Properties.ReadOnly = false;
                    bteDepartment.Properties.Buttons[0].Enabled = true;
                    bteSupplier.Properties.ReadOnly = false;
                    bteSupplier.Properties.Buttons[0].Enabled = true;
                    mmoRemark.Properties.ReadOnly = false;
                    txtCreator.Properties.ReadOnly = false;
                    txtChecker.Properties.ReadOnly = true;

                    grvBody.OptionsBehavior.Editable = true;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

                    lblStatus.Text = "草稿";
                    break;
            }
        }

        void grvBody_DoubleClick(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private bool LoadNewCode()
        {
            string code;
            do
            {
                code = Common.Common.GetOrderCode(OrderType);
                if (code != null)
                {
                    break;
                }
            }
            while (DialogResult.Yes == XtraMessageBox.Show("获取单据编号失败\r重新获取（若多次失败，请联系管理员）？", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2));

            if (code != null)
            {
                txtCode.Text = code;
                return true;
            }
            else
            {
                pnlTools.Enabled = false;
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                return false;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            btnSave.Focus();

            if (DepartmentID == 0)
            {
                XtraMessageBox.Show("请输入入库部门。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteDepartment.Focus();
                return;
            }
            else if (SupplierID == 0)
            {
                XtraMessageBox.Show("请输入供应商。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteSupplier.Focus();
                return;
            }
            else if ((grdBody.DataSource as DataTable).Rows.Count == 0)
            {
                XtraMessageBox.Show("请填写入库内容。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (txtCreator.Text.Trim().Length == 0)
            {
                XtraMessageBox.Show("请填写建单人。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            for (int i = 0; i < grvBody.RowCount; i++)
            {
                grvBody.FocusedRowHandle = i;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["ProductCode"];
                view.FocusedColumn.View.ShowEditor();
                if (!view.ValidateEditor()) return;

                view.FocusedColumn = view.Columns["Price"];
                view.FocusedColumn.View.ShowEditor();
                if (!view.ValidateEditor()) return;

                view.FocusedColumn = view.Columns["Qty"];
                view.FocusedColumn.View.ShowEditor();
                if (!view.ValidateEditor()) return;

                view.FocusedColumn = view.Columns["WarehouseCode"];
                view.FocusedColumn.View.ShowEditor();
                if (!view.ValidateEditor()) return;
            }

            if (ID <= 0)
            {
                SaveNew();
            }
            else
            {
                SaveModify();
            }
        }
        /// <summary>
        /// 保存修改
        /// </summary>
        private void SaveModify()
        {
            var bll = new DMZS.BLL.InStock();
            var model = new DMZS.Model.InStock();

            model.Date = DateTime.Now;
            model.Number = txtCode.Text;
            model.VchType = OrderTypeID;
            model.Comment = mmoRemark.Text;
            model.btypeid = SupplierID.ToString();
            model.etypeid = txtCreator.Text.Trim();
            model.ifcheck = 0;
            model.checke = string.Empty;
            model.InputNo = txtOperator.Text.Trim();
            model.draft = 0;
            model.DeptID = DepartmentID.ToString();
            model.isScan = chkIsScan.Checked ? 1 : 0;
            model.SalePurpose = string.Empty;
            model.Tbody = grdBody.DataSource as DataTable;
            model.Vchcode = ID;
            model.Tbarcode = Barcodes;

            var result = bll.UpdateExpand(model);

            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("保存成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (result == -10021)
            {
                XtraMessageBox.Show("单据类型查找失败，建议关闭选项卡。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (result == -10022)
            {
                XtraMessageBox.Show("该供应商被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteSupplier.Focus();
                bteSupplier.SelectAll();
            }
            else if (result == -10023)
            {
                XtraMessageBox.Show("该部门被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteSupplier.Focus();
                bteSupplier.SelectAll();
            }
        }

        /// <summary>
        /// 保存新增
        /// </summary>
        private void SaveNew()
        {
            var bll = new DMZS.BLL.InStock();
            var model = new DMZS.Model.InStock();

            model.Date = DateTime.Now;
            model.Number = txtCode.Text;
            model.VchType = OrderTypeID;
            model.Comment = mmoRemark.Text;
            model.btypeid = SupplierID.ToString();
            model.etypeid = txtCreator.Text.Trim();
            model.ifcheck = 0;
            model.checke = string.Empty;
            model.InputNo = txtOperator.Text.Trim();
            model.draft = 0;
            model.DeptID = DepartmentID.ToString();
            model.isScan = chkIsScan.Checked ? 1 : 0;
            model.SalePurpose = string.Empty;
            model.Tbody = grdBody.DataSource as DataTable;
            model.Tbarcode = Barcodes;

            var result = bll.AddExpand(model);
            if (result > 0)
            {
                ID = result;
                LoadData();
                XtraMessageBox.Show("保存成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (result == -10021)
            {
                XtraMessageBox.Show("单据类型查找失败，建议关闭选项卡。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (result == -10022)
            {
                XtraMessageBox.Show("该供应商被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteSupplier.Focus();
                bteSupplier.SelectAll();
            }
            else if (result == -10023)
            {
                XtraMessageBox.Show("该部门被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteSupplier.Focus();
                bteSupplier.SelectAll();
            }
        }


        private void bteDepartment_Enter(object sender, EventArgs e)
        {
            if (DepartmentCode != string.Empty)
            {
                bteDepartment.Text = DepartmentCode;
            }
        }

        private void bteDepartment_Leave(object sender, EventArgs e)
        {
            bteDepartment.Text = DepartmentName;
        }

        private void bteDepartment_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13 || e.KeyChar == '\t')
            {
                if (!ValidateDept())
                {
                    XtraMessageBox.Show("不存在该部门编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bteDepartment.Focus();
                    bteDepartment.SelectAll();
                }
                else
                {
                    SendKeys.Send("{TAB}");
                }
            }
        }

        /// <summary>
        /// 验证部门
        /// </summary>
        /// <returns></returns>
        private bool ValidateDept()
        {
            if (bteDepartment.Text.Trim().Length == 0)
            {
                DepartmentID = 0;
                DepartmentName = string.Empty;
                DepartmentCode = string.Empty;
                return true;
            }

            if (bteDepartment.Text.Trim() == DepartmentCode)
            {
                bteDepartment.Text = DepartmentName;
                return true;
            }

            var bll = new DMZS.BLL.DepartmentNew();
            var row = bll.GetRecordByCode(bteDepartment.Text.Trim());
            if (row != null)
            {
                DepartmentID = Convert.ToInt32(row["ID"]);
                DepartmentCode = row["Code"].ToString();
                DepartmentName = row["Name"].ToString();
                bteDepartment.Text = DepartmentName;
                return true;
            }
            else
            {
                DepartmentID = 0;
                DepartmentCode = string.Empty;
                DepartmentName = string.Empty;
                return false;
            }
        }

        private void bteSupplier_Enter(object sender, EventArgs e)
        {
            if (SupplierCode != string.Empty)
            {
                bteSupplier.Text = SupplierCode;
            }
        }

        private void bteSupplier_Leave(object sender, EventArgs e)
        {
            bteSupplier.Text = SupplierName;
        }

        private void bteSupplier_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!ValidateSupplier())
                {
                    XtraMessageBox.Show("不存在该供应商编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bteSupplier.Focus();
                    bteSupplier.SelectAll();
                }
                else
                {
                    SendKeys.Send("{TAB}");
                }
            }
        }

        /// <summary>
        /// 验证供应商
        /// </summary>
        /// <returns></returns>
        private bool ValidateSupplier()
        {
            if (bteSupplier.Text.Trim().Length == 0)
            {
                SupplierID = 0;
                SupplierName = string.Empty;
                SupplierCode = string.Empty;
                return true;
            }

            if (bteSupplier.Text.Trim() == SupplierCode)
            {
                bteSupplier.Text = SupplierName;
                return true;
            }

            var bll = new DMZS.BLL.Supplier();
            var row = bll.GetRecordByCode(bteSupplier.Text.Trim());
            if (row != null)
            {
                SupplierID = Convert.ToInt32(row["ID"]);
                SupplierCode = row["Code"].ToString();
                SupplierName = row["Name"].ToString();
                bteSupplier.Text = SupplierName;
                return true;
            }
            else
            {
                SupplierID = 0;
                SupplierName = string.Empty;
                SupplierCode = string.Empty;
                return false;
            }
        }

        private void grvBody_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "Qty" || e.Column.FieldName == "Price")
            {
                decimal qty, price;
                if (grvBody.GetFocusedRowCellValue("Qty") == null
                    || grvBody.GetFocusedRowCellValue("Qty") == DBNull.Value
                    || grvBody.GetFocusedRowCellValue("Qty").ToString() == string.Empty)
                {
                    qty = 0;
                }
                else
                {
                    qty = Convert.ToDecimal(grvBody.GetFocusedRowCellValue("Qty"));
                }

                if (grvBody.GetFocusedRowCellValue("Price") == null
                   || grvBody.GetFocusedRowCellValue("Price") == DBNull.Value
                   || grvBody.GetFocusedRowCellValue("Price").ToString() == string.Empty)
                {
                    price = 0;
                }
                else
                {
                    price = Convert.ToDecimal(grvBody.GetFocusedRowCellValue("Price"));
                }

                grvBody.SetRowCellValue(e.RowHandle, "SubTotal", qty * price);
            }
        }

        private void grvBody_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            var obj = grvBody.GetRowCellValue(e.RowHandle, "ProductCode");
            if (obj == null || obj.ToString().Trim().Length == 0)
            {
                e.ErrorText = " 请输入产品编号\r";
                e.Valid = false;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["ProductCode"];
                view.FocusedColumn.View.ShowEditor();

                return;
            }
            var qty = grvBody.GetRowCellValue(e.RowHandle, "Qty");
            if (qty.ToString() == string.Empty || Convert.ToInt32(qty) == 0)
            {
                e.ErrorText = " 请输入正确数量\r";
                e.Valid = false;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["Qty"];
                view.FocusedColumn.View.ShowEditor();
                return;
            }
            var price = grvBody.GetRowCellValue(e.RowHandle, "Price");
            if (price.ToString() == string.Empty || Convert.ToDecimal(price) < 0)
            {
                e.ErrorText = " 请输入正确价格\r";
                e.Valid = false;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["Price"];
                view.FocusedColumn.View.ShowEditor();
                return;
            }
            var warehouse = grvBody.GetRowCellValue(e.RowHandle, "WarehouseCode");
            if (warehouse == null || warehouse.ToString().Trim().Length == 0)
            {
                e.ErrorText = " 请输入仓库编号\r";
                e.Valid = false;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["WarehouseCode"];
                view.FocusedColumn.View.ShowEditor();
                return;
            }
        }


        private void grvBody_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            switch (grvBody.FocusedColumn.FieldName)
            {
                case "ProductCode":
                    var code = e.Value;
                    if (code == null || code.ToString().Trim().Length == 0)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "ProductID", 0);
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "ProductName", "");
                        return;
                    }
                    var bll = new DMZS.BLL.Product();
                    var row = bll.GetRecordByCode(code.ToString().Trim());
                    if (row != null)
                    {
                        var dt = grdBody.DataSource as DataTable;
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            if (grvBody.FocusedRowHandle != grvBody.GetRowHandle(i))
                            {
                                if (dt.Rows[i]["ProductCode"].ToString().Trim() == row["Code"].ToString())
                                {
                                    e.ErrorText = "编号重复";
                                    e.Valid = false;
                                    return;
                                }
                            }
                        }

                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "ProductID", Convert.ToInt64(row["ID"].ToString()));
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "ProductName", row["Name"].ToString());
                    }
                    else
                    {
                        e.ErrorText = "该产品编号不存在";
                        e.Valid = false;
                        return;
                    }
                    e.Value = row["Code"].ToString();
                    break;

                case "WarehouseCode":
                    var value = e.Value;
                    if (value == null || value.ToString().Trim().Length == 0)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "WarehouseID", 0);
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "WarehouseName", "");
                        return;
                    }
                    var bll1 = new DMZS.BLL.Warehouse();
                    var row1 = bll1.GetRecordByCode(value.ToString().Trim());
                    if (row1 != null)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "WarehouseID", Convert.ToInt64(row1["ID"].ToString()));
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "WarehouseName", row1["Name"].ToString());
                    }
                    else
                    {
                        e.ErrorText = "该仓库编号不存在";
                        e.Valid = false;
                    }
                    e.Value = value.ToString().Trim();
                    break;

                case "Qty":
                    var qty = e.Value;
                    if (qty == null || Convert.ToInt32(qty) <= 0)
                    {
                        e.ErrorText = "请输入正确数量";
                        e.Valid = false;
                    }
                    break;

                case "Price":
                    var price = e.Value;
                    if (price == null || Convert.ToDecimal(price) < 0)
                    {
                        e.ErrorText = "请输入正确价格";
                        e.Valid = false;
                    }
                    break;
                case "UnitBaseCode":
                    var unit = e.Value;
                    if (unit == null || unit.ToString().Trim().Length == 0)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "unit", 0);
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "UnitBaseName", "");
                        return;
                    }
                    var bll2 = new DMZS.BLL.UnitBase();
                    var row2 = bll2.GetRecordByCode(unit.ToString().Trim());
                    if (row2 != null)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "unit", Convert.ToInt64(row2["UnitBaseID"].ToString()));
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "UnitBaseName", row2["BaseName"].ToString());
                    }
                    else
                    {
                        e.ErrorText = "该单位编号不存在";
                        e.Valid = false;
                    }
                    e.Value = unit.ToString().Trim();
                    break;
            }

            //grvBody.UpdateCurrentRow();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (ID <= 0)
            {
                return;
            }
            else
            {
                LoadData();
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (ID <= 0)
            {
                return;
            }
            NewRecord();
        }



        private void tmiDelete_Click(object sender, EventArgs e)
        {
            int[] selects = grvBody.GetSelectedRows();
            foreach (int i in selects)
            {
                if (grvBody.GetRowCellValue(i, "ProductID") != null
                    && grvBody.GetRowCellValue(i, "ProductID") != DBNull.Value
                    && grvBody.GetRowCellValue(i, "ProductID").ToString().Trim() != "")
                {
                    DataRow[] rows = Barcodes.Select("ProductID=" + grvBody.GetRowCellValue(i, "ProductID").ToString());
                    foreach (DataRow row in rows)
                    {
                        Barcodes.Rows.Remove(row);
                    }
                }
            }
            Barcodes.AcceptChanges();

            grvBody.DeleteSelectedRows();
            (grdBody.DataSource as DataTable).AcceptChanges();

            //int[] selects = grvBody.GetSelectedRows();
            //foreach (int i in selects)
            //{
            //    grvBody.GetDataRow(selects[i]).Delete();
            //}
            //((DataRowView)grvBody.SelectedRows[0].DataBoundItem).Row.Delete();
            //((DataRowView)gridView1.SelectRows[0]).Row.Delete();

            //(grdBody.DataSource as DataTable).Rows[0].Delete();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var frm = new DialogForm.FrmInStock_dlg();
            frm.ReturnID += new DialogForm.FrmInStock_dlg.ReturnIDEventHandler(frm_ReturnID);
            frm.ShowDialog();
        }

        private void frm_ReturnID(long ID)
        {
            this.ID = ID;
            LoadData();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (ID <= 0)
            {
                NewRecord();
            }
            else
            {
                if (DialogResult.No == XtraMessageBox.Show("确认删除?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                {
                    return;
                }

                var bll = new DMZS.BLL.InStock();
                var result = bll.DeleteExpand(ID, OrderTypeID);
                if (result == -10031)
                {
                    XtraMessageBox.Show("该条记录已被审核，无法删除请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10032)
                    {
                        XtraMessageBox.Show("该条记录已被关闭，无法删除请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        NewRecord();
                    }
                }
            }
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (txtChecker.Text.Trim().Length == 0)
            {
                XtraMessageBox.Show("请输入审核人。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var bll = new DMZS.BLL.InStock();
            var result = bll.Check(ID, txtChecker.Text.Trim(), OrderTypeID);
            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("审核成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -1000)
                {
                    NewRecord();
                    XtraMessageBox.Show("该条记录已被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10001)
                    {
                        XtraMessageBox.Show("该条记录已被其他用户审核，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (result == -1003)
                        {
                            XtraMessageBox.Show("该条记录已被关闭，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            XtraMessageBox.Show("审核失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        private void btnUnCheck_Click(object sender, EventArgs e)
        {
            var bll = new DMZS.BLL.InStock();
            var result = bll.UnCheck(ID, OrderTypeID);
            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("反审成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -1000)
                {
                    NewRecord();
                    XtraMessageBox.Show("该条记录已被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10002)
                    {
                        XtraMessageBox.Show("该条记录已被其他用户反审核，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (result == -1003)
                        {
                            XtraMessageBox.Show("该条记录已被关闭，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            XtraMessageBox.Show("反审失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            var bll = new DMZS.BLL.InStock();
            var result = bll.Close(ID, OrderTypeID);
            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("关闭成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -1000)
                {
                    NewRecord();
                    XtraMessageBox.Show("该条记录已被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10002)
                    {
                        XtraMessageBox.Show("该条记录已被其他用户反审核，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (result == -1003)
                        {
                            XtraMessageBox.Show("该条记录已被其他用户关闭，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            XtraMessageBox.Show("关闭失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 更改是否扫描时刷新网格状态
        /// </summary>
        /// <param name="IsScan"></param>
        private void RefreshGrid(bool IsScan)
        {
            if (IsScan)
            {
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                grvBody.Columns["ProductCode"].OptionsColumn.AllowEdit = false;
                grvBody.Columns["Qty"].OptionsColumn.AllowEdit = false;
            }
            else
            {
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
                grvBody.Columns["ProductCode"].OptionsColumn.AllowEdit = true;
                grvBody.Columns["Qty"].OptionsColumn.AllowEdit = true;
            }
        }

        private void btnScan_Click(object sender, EventArgs e)
        {
            if ((grdBody.DataSource as DataTable).Rows.Count != 0 && !chkIsScan.Checked)
            {
                //手动改扫描
                DialogResult result = XtraMessageBox.Show("已有手动填写的数据，是否清空？", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3);
                switch (result)
                {
                    case DialogResult.OK:
                        grvBody.SelectAll();
                        grvBody.DeleteSelectedRows();
                        (grdBody.DataSource as DataTable).AcceptChanges();

                        break;
                    case DialogResult.Cancel:
                        return;
                }
            }

            chkIsScan.CheckedChanged -= new EventHandler(chkIsScan_CheckedChanged);
            chkIsScan.Checked = true;
            chkIsScan.CheckedChanged += new EventHandler(chkIsScan_CheckedChanged);
            RefreshGrid(true);

            grvBody.ValidateRow -= new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(grvBody_ValidateRow);
            grvBody.ValidatingEditor -= new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(grvBody_ValidatingEditor);

            FrmInStock_scan frmScan = new FrmInStock_scan();
            frmScan.ReturnID += new FrmInStock_scan.ReturnIDEventHandler(frmScan_ReturnID);
            frmScan.ShowDialog();

            grvBody.ValidateRow += new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(grvBody_ValidateRow);
            grvBody.ValidatingEditor += new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(grvBody_ValidatingEditor);

        }

        /// <summary>
        /// 处理扫描结果
        /// </summary>
        /// <param name="ProductCode"></param>
        Hashtable frmScan_ReturnID(Hashtable BarcodeInfo)
        {
            Hashtable htb = new Hashtable();
            htb.Add("ID", 0);
            htb.Add("Message", "");

            //+检查是否已扫描过，-检查是否已扫描过
            if (Convert.ToInt32(BarcodeInfo["Direction"]) > 0)
            {
                //加
                return AddBarcode(BarcodeInfo, htb);
            }
            else
            {
                //减
                return RemoveBarcode(BarcodeInfo, htb);
            }
        }

        /// <summary>
        /// 添加一条扫描条码
        /// </summary>
        /// <param name="BarcodeInfo"></param>
        /// <param name="htb"></param>
        /// <returns></returns>
        private Hashtable AddBarcode(Hashtable BarcodeInfo, Hashtable htb)
        {
            int status = Convert.ToInt32(BarcodeInfo["Status"]);
            if (status == 0)
            {
                //非本系统打印
                htb["ID"] = -1;
                htb["Message"] = "非本系统打印条码";
                return htb;
            }

            DataRow[] rows = Barcodes.Select("Code='" + BarcodeInfo["Code"].ToString() + "'");
            if (rows.Length > 0)
            {
                //重复扫描
                htb["ID"] = -1;
                htb["Message"] = BarcodeInfo["Code"].ToString() + " 已在关联条码单中，无需重复扫描";
                return htb;
            }

            if (status == 10)
            {
                //入库待审
                if (ID == 0)
                {
                    htb["ID"] = -1;
                    htb["Message"] = BarcodeInfo["Code"].ToString() + " 已被其他入库单占用，等待审核。无法扫入";
                }
                else
                {
                    DMZS.BLL.Barcode bll = new DMZS.BLL.Barcode();
                    if (bll.IfInOrder(Convert.ToInt64(BarcodeInfo["ID"]), ID, DMZS.Model.DlyndxOrder.OrderType.RKD))
                    {
                        //移除掉，再扫入
                        AddBarcodeAction(BarcodeInfo, htb);
                    }
                    else
                    {
                        htb["ID"] = -1;
                        htb["Message"] = BarcodeInfo["Code"].ToString() + " 已被其他入库单占用，等待审核。无法扫入";
                    }
                }
            }
            else if (status == 11)
            {
                //入库已审核
                htb["ID"] = -1;
                htb["Message"] = BarcodeInfo["Code"].ToString() + " 已入库审核。无法扫入";
            }
            else if (status == 20)
            {
                //出库待审
                htb["ID"] = -1;
                htb["Message"] = BarcodeInfo["Code"].ToString() + " 已被出库单占用，等待审核。无法扫入";
            }
            else if (status == 21)
            {
                //出库已审核
                htb["ID"] = -1;
                htb["Message"] = BarcodeInfo["Code"].ToString() + " 已出库。无法扫入";
            }
            else if (status == 30)
            {
                //退货待审
                htb["ID"] = -1;
                htb["Message"] = BarcodeInfo["Code"].ToString() + " 已被其他退货单占用，等待审核。无法扫入";
            }
            else if (status == 31 || status == 1)
            {
                //退货已审核 或 已打印
                AddBarcodeAction(BarcodeInfo, htb);
            }

            return htb;
        }

        /// <summary>
        /// 添加条码
        /// </summary>
        /// <param name="BarcodeInfo"></param>
        /// <param name="htb"></param>
        private void AddBarcodeAction(Hashtable BarcodeInfo, Hashtable htb)
        {
            int i = 0;
            for (i = 0; i < grvBody.RowCount; i++)
            {
                if (grvBody.GetRowCellValue(i, "ProductCode").ToString() == BarcodeInfo["ProductCode"].ToString())
                {
                    int orderTypeID = grvBody.GetRowCellValue(i, "OrderType") == DBNull.Value ? 0 : Convert.ToInt32(grvBody.GetRowCellValue(i, "OrderType"));
                    if (Convert.ToInt32(BarcodeInfo["OrderTypeID"]) != orderTypeID)
                    {
                        htb["ID"] = -1;
                        htb["Message"] = "当前版本不支持一张单子下有不同来源的相同产品";
                        return;
                    }
                    else
                    {
                        object obj = grvBody.GetRowCellValue(i, "Qty");
                        int newVariable = obj == DBNull.Value ? 0 : Convert.ToInt32(obj);
                        grvBody.SetRowCellValue(i, "Qty", newVariable + 1);
                    }
                    break;
                }
            }

            if (i == grvBody.RowCount)
            {
                grvBody.AddNewRow();
                grvBody.SetFocusedRowCellValue("ProductID", BarcodeInfo["ProductID"]);
                grvBody.SetFocusedRowCellValue("ProductCode", BarcodeInfo["ProductCode"]);
                grvBody.SetFocusedRowCellValue("ProductName", BarcodeInfo["ProductName"]);
                grvBody.SetFocusedRowCellValue("Qty", 1);
                grvBody.SetFocusedRowCellValue("unit", BarcodeInfo["UnitBaseID"]);
                grvBody.SetFocusedRowCellValue("UnitBaseCode", BarcodeInfo["UnitBaseCode"]);
                grvBody.SetFocusedRowCellValue("UnitBaseName", BarcodeInfo["UnitBaseName"]);
                grvBody.SetFocusedRowCellValue("OrderType", BarcodeInfo["OrderTypeID"]);
                grvBody.SetFocusedRowCellValue("OrderCode", BarcodeInfo["OrderID"]);
                grvBody.SetFocusedRowCellValue("OrderNumber", BarcodeInfo["OrderCode"]);
                grvBody.SetFocusedRowCellValue("OrderDlyCode", BarcodeInfo["OrderLineID"]);
                grvBody.SetFocusedRowCellValue("OrderTypeName", BarcodeInfo["OrderTypeName"]);
            }

            grvBody.UpdateCurrentRow();

            DataRow row = Barcodes.NewRow();
            row["ID"] = BarcodeInfo["ID"];
            row["Code"] = BarcodeInfo["Code"];
            row["ProductID"] = BarcodeInfo["ProductID"];
            row["OrderTypeID"] = OrderTypeID;

            Barcodes.Rows.Add(row);
            htb["ID"] = 1;
            htb["Message"] = BarcodeInfo["Code"].ToString() + " 扫入成功";
        }

        /// <summary>
        /// 移除一条扫描条码
        /// </summary>
        /// <param name="BarcodeInfo"></param>
        /// <param name="htb"></param>
        /// <returns></returns>
        private Hashtable RemoveBarcode(Hashtable BarcodeInfo, Hashtable htb)
        {
            DataRow[] rows = Barcodes.Select("Code='" + BarcodeInfo["Code"].ToString() + "'");
            if (rows.Length > 0)
            {
                int i = 0;
                for (i = 0; i < grvBody.RowCount; i++)
                {
                    if (grvBody.GetRowCellValue(i, "ProductCode").ToString() == BarcodeInfo["ProductCode"].ToString())
                    {
                        object obj = grvBody.GetRowCellValue(i, "Qty");
                        int newVariable = obj == DBNull.Value ? 0 : Convert.ToInt32(obj);
                        if (newVariable > 1)
                        {
                            grvBody.SetRowCellValue(i, "Qty", newVariable - 1);
                        }
                        else
                        {
                            grvBody.DeleteRow(i);
                            (grdBody.DataSource as DataTable).AcceptChanges();
                        }
                        break;
                    }
                }

                foreach (DataRow row in rows)
                {
                    Barcodes.Rows.Remove(row);
                }
                Barcodes.AcceptChanges();
                htb["ID"] = 1;
                htb["Message"] = BarcodeInfo["Code"].ToString() + " 移除成功";
            }
            else
            {
                htb["ID"] = 0;
                htb["Message"] = BarcodeInfo["Code"].ToString() + " 未在关联的条码单，无需移除";
            }

            return htb;
        }

        private void chkIsScan_CheckedChanged(object sender, EventArgs e)
        {
            int rowCount = (grdBody.DataSource as DataTable).Rows.Count;
            //if (rowCount == 0) return;

            if (chkIsScan.Checked)
            {
                //手动改扫描
                if (rowCount > 0)
                {
                    DialogResult result = XtraMessageBox.Show("已有手动填写的数据，是否清空？", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3);
                    switch (result)
                    {
                        case DialogResult.OK:
                            grvBody.SelectAll();
                            grvBody.DeleteSelectedRows();
                            (grdBody.DataSource as DataTable).AcceptChanges();

                            RefreshGrid(true);
                            break;
                        case DialogResult.Cancel:
                            chkIsScan.CheckedChanged -= new EventHandler(chkIsScan_CheckedChanged);
                            chkIsScan.Checked = false;
                            chkIsScan.CheckedChanged += new EventHandler(chkIsScan_CheckedChanged);
                            break;
                    }
                }
                else
                {
                    RefreshGrid(true);
                }
            }
            else
            {
                //扫描改手动
                if (rowCount > 0)
                {
                    DialogResult result = XtraMessageBox.Show("已有扫描的数据，是否清空？", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3);
                    switch (result)
                    {
                        case DialogResult.OK:
                            grvBody.SelectAll();
                            grvBody.DeleteSelectedRows();
                            (grdBody.DataSource as DataTable).AcceptChanges();

                            RefreshGrid(false);
                            break;
                        case DialogResult.Cancel:
                            chkIsScan.CheckedChanged -= new EventHandler(chkIsScan_CheckedChanged);
                            chkIsScan.Checked = true;
                            chkIsScan.CheckedChanged += new EventHandler(chkIsScan_CheckedChanged);
                            break;
                    }
                }
                else
                {
                    RefreshGrid(false);
                }
            }
        }

        private void bteDepartment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmDepartment_dlg frmDepartment_dlg = new DialogForm.FrmDepartment_dlg();
            frmDepartment_dlg.ReturnList += new DialogForm.FrmDepartment_dlg.ReturnListEventHandler(frmDepartment_dlg_ReturnList);
            frmDepartment_dlg.ShowDialog();
        }

        void frmDepartment_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists == null) return;

            DepartmentID = Convert.ToInt32(lists[0]["ID"]);
            DepartmentCode = lists[0]["Code"].ToString();
            DepartmentName = lists[0]["Name"].ToString();
            bteDepartment.Text = DepartmentCode;
        }

        private void bteSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmSupplier_dlg frmSupplier_dlg = new DialogForm.FrmSupplier_dlg();
            frmSupplier_dlg.ReturnList += new DialogForm.FrmSupplier_dlg.ReturnListEventHandler(frmSupplier_dlg_ReturnList);
            frmSupplier_dlg.ShowDialog();
        }

        void frmSupplier_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists.Count == 0) return;

            SupplierID = Convert.ToInt32(lists[0]["ID"]);
            SupplierCode = lists[0]["Code"].ToString();
            SupplierName = lists[0]["Name"].ToString();
            bteSupplier.Text = SupplierCode;
        }

        private void repProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmProduct_dlg frmProduct_dlg = new DialogForm.FrmProduct_dlg();
            frmProduct_dlg.MultiSelect = true;
            frmProduct_dlg.ReturnList += new DialogForm.FrmProduct_dlg.ReturnListEventHandler(frmProduct_dlg_ReturnList);

            grvBody.ValidateRow -= new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(grvBody_ValidateRow);
            grvBody.ValidatingEditor -= new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(grvBody_ValidatingEditor);

            frmProduct_dlg.ShowDialog();

            grvBody.ValidateRow += new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(grvBody_ValidateRow);
            grvBody.ValidatingEditor += new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(grvBody_ValidatingEditor);

        }

        void frmProduct_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists == null) return;

            foreach (DataRow row in lists.ToArray())
            {
                int i = 0;
                DataTable dt = (grdBody.DataSource as DataTable);
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["ProductID"].ToString() == row["ID"].ToString())
                    {
                        //int orderTypeID = grvBody.GetRowCellValue(i, "OrderType") == DBNull.Value ? 0 : Convert.ToInt32(grvBody.GetRowCellValue(i, "OrderType"));
                        //if (Convert.ToInt32(BarcodeInfo["OrderTypeID"]) != orderTypeID)
                        //{
                        //    htb["ID"] = -1;
                        //    htb["Message"] = "当前版本不支持一张单子下有不同来源的相同产品";
                        //    return;
                        //}
                        //else
                        //{
                        //    object obj = grvBody.GetRowCellValue(i, "Qty");
                        //    int newVariable = obj == DBNull.Value ? 0 : Convert.ToInt32(obj);
                        //    grvBody.SetRowCellValue(i, "Qty", newVariable + 1);
                        //}
                        break;
                    }
                }

                if (i == dt.Rows.Count)
                {
                    if (grvBody.GetFocusedRowCellValue("ProductID") == null
                       || grvBody.GetFocusedRowCellValue("ProductID") == DBNull.Value
                       || grvBody.GetFocusedRowCellValue("ProductID").ToString() != row["ID"].ToString())
                    {
                        grvBody.AddNewRow();
                        grvBody.SetFocusedRowCellValue("ProductID", row["ID"]);
                        grvBody.SetFocusedRowCellValue("ProductCode", row["Code"]);
                        grvBody.SetFocusedRowCellValue("ProductName", row["Name"]);
                        grvBody.SetFocusedRowCellValue("Qty", 1);
                        grvBody.SetFocusedRowCellValue("unit", row["UnitID"]);
                        grvBody.SetFocusedRowCellValue("UnitBaseCode", row["BaseCode"]);
                        grvBody.SetFocusedRowCellValue("UnitBaseName", row["BaseName"]);
                        grvBody.SetFocusedRowCellValue("OrderType", 0);
                        grvBody.SetFocusedRowCellValue("OrderCode", 0);
                        grvBody.SetFocusedRowCellValue("OrderNumber", "");
                        grvBody.SetFocusedRowCellValue("OrderDlyCode", 0);
                        grvBody.SetFocusedRowCellValue("OrderTypeName", "");

                        grvBody.UpdateCurrentRow();
                    }
                }

            }
        }

        private void repUnitBaseCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmUnitBase_dlg frmUnitBase_dlg = new DialogForm.FrmUnitBase_dlg();
            frmUnitBase_dlg.MultiSelect = false;
            frmUnitBase_dlg.ReturnList += new DialogForm.FrmUnitBase_dlg.ReturnListEventHandler(frmUnitBase_dlg_ReturnList);
            frmUnitBase_dlg.ShowDialog();
        }

        void frmUnitBase_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists == null) return;

            grvBody.SetFocusedRowCellValue("unit", lists[0]["UnitBaseID"]);
            grvBody.SetFocusedRowCellValue("UnitBaseCode", lists[0]["BaseCode"]);
            grvBody.SetFocusedRowCellValue("UnitBaseName", lists[0]["BaseName"]);
        }

        private void repWarehouse_ButtonClick_1(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmWarehouse_dlg frmWarehouse_dlg = new DialogForm.FrmWarehouse_dlg();
            frmWarehouse_dlg.ReturnList += new DialogForm.FrmWarehouse_dlg.ReturnListEventHandler(frmWarehouse_dlg_ReturnList);
            frmWarehouse_dlg.ShowDialog();
        }

        void frmWarehouse_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists == null) return;

            grvBody.SetFocusedRowCellValue("WarehouseID", lists[0]["ID"]);
            grvBody.SetFocusedRowCellValue("WarehouseCode", lists[0]["Code"]);
            grvBody.SetFocusedRowCellValue("WarehouseName", lists[0]["Name"]);
        }

    }
}
